<template>
  <el-table :data="filteredCourses" style="width: 100%" :fit="true">
    <el-table-column label="课程ID" prop="id" align="center" show-overflow-tooltip />
    <el-table-column label="课程名称" prop="name" align="center" show-overflow-tooltip />
    <el-table-column label="学分" prop="point" align="center" show-overflow-tooltip />
    <el-table-column label="学时" prop="time" align="center" show-overflow-tooltip />

    <!-- 右侧操作列 -->
    <el-table-column label="操作" align="center">
      <template #header>
        <el-input
            v-model="keyword"
            size="default"
            placeholder="搜索课程"
            clearable
            style="width: 180px;"
        />
      </template>
      <template #default="scope">
        <el-button size="small" type="primary" @click="editCourse(scope.row)">
          编辑
        </el-button>
        <el-button size="small" type="danger" @click="deleteCourse(scope.row.id)">
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 分页组件 -->
  <el-pagination background layout="prev, pager, next" :total="total" :page-size="pageSize" @current-change="loadCourse"/>

  <!-- 编辑课程对话框 -->
  <el-dialog title="编辑课程" v-model="dialogFormVisible" width="500px">
    <el-form :model="course" ref="courseForm" label-width="80px">
      <el-form-item label="课程名称">
        <el-input v-model="course.name" />
      </el-form-item>
      <el-form-item label="学分">
        <el-input v-model="course.point" type="number" />
      </el-form-item>
      <el-form-item label="学时">
        <el-input v-model="course.time" type="number" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogFormVisible = false">取消</el-button>
      <el-button type="primary" @click="saveCourse">保存</el-button>
    </template>
  </el-dialog>
</template>

<script>
export default {
  name: "CourseView",
  data() {
    return {
      courses: [], // 课程数据
      keyword: "",  // 搜索关键字
      current: 1, //当前页
      pageSize: 10, //页大小
      total: 10,   //总数
      dialogFormVisible: false,  //对话框是否显示
      course: {} //当前课程
    };
  },
  computed: {
    // 根据关键词过滤课程列表
    filteredCourses() {
      return this.courses.filter(course =>
          course.name.includes(this.keyword)
      );
    }
  },
  methods: {
    // 加载课程数据
    loadCourses() {
      this.$axios.get("/findCourses").then(result => {
        if (result.data.code === 200) {
          this.courses = result.data.data; // 将接口返回的课程数据赋值给 courses
        } else {
          this.$message.error("加载课程失败"); // 如果接口返回的代码不是 200，提示失败
        }
      }).catch(error => {
        console.error("API 请求错误", error);
        this.$message.error("请求数据失败"); // 请求失败时提示错误
      });
    },

    // 加载课程数据（分页版）
    loadCourse(current) {
      this.current = current;
      this.$axios.get(`/findCoursePage?current=${this.current}&pageSize=${this.pageSize}`)
          .then(result => {
            if (result.data.code === 200) {
              this.courses = result.data.data.data;
              this.total = result.data.data.total;
            }
          });
    },

    // 编辑课程
    editCourse(course) {
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs.courseForm && this.$refs.courseForm.clearValidate();
      });

      // 课程回显效果
      this.course = JSON.parse(JSON.stringify(course)); // 深克隆，避免数据共享
    },

    saveCourse() {
      this.$axios.post("/updatecourse", this.course).then(result => {
        if (result.data.code === 200) {
          this.$message.success("编辑成功");
          this.dialogFormVisible = false;
          this.loadCourse(this.current); // 重新加载数据
        } else {
          this.$message.error("编辑失败，请稍后重试");
        }
      }).catch(error => {
        this.$message.error("请求失败: " + error.message);
      });
    },

    // 删除课程
 /*   deleteCourse(id) {
      this.$confirm("确定删除该学生吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.$axios
            .post("/removecourse", { id }) // 发送删除请求到后端
            .then(result => {
              if (result.data.code === 200) {
                this.courses = this.courses.filter(course => course.id !== id);
                this.$message.success("删除成功");
              } else {
                this.$message.error("删除失败，请稍后重试");
              }
            })
            .catch(() => {
              this.$message.error("请求失败，请检查网络");
            });
      }).catch(() => {
        this.$message.info("已取消删除");
      });
    },*/
    deleteCourse(id) {
      this.$confirm("确定删除该课程吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.$axios
            .post("/removecourse", { id })
            .then(result => {
              console.log(result); // 打印返回结果
              if (result.data.code === 200) {
                this.courses = this.courses.filter(course => course.id !== id);
                this.$message.success("删除成功");
              } else {
                this.$message.error("删除失败，请稍后重试");
              }
            })
            .catch(() => {
              this.$message.error("请求失败，请检查网络");
            });
      }).catch(() => {
        this.$message.info("已取消删除");
      });
    }

  },
  mounted() {
    this.loadCourses(); // 组件加载时请求课程数据
    this.loadCourse(1); // 加载第一页数据
  }
};
</script>

<style scoped>
.el-table {
  margin-top: 10px;
  border-radius: 8px;
}

.el-button {
  margin-right: 5px;
}
</style>
